<?php

namespace App\Http\Controllers;

use App\Http\Requests\GroupAdd;
use App\Http\Requests\GroupJoin as GroupJoinP;
use App\Models\ArticleView;
use App\Models\GroupJoin;
use App\Models\Group;
use App\Models\MyGroup;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GroupController extends BaseController
{
    // 加入圈子
    public function join(GroupJoinP $request)
    {
        // 查看圈子是否是自己建立的
        $group = Group::query()
            ->where(['id' => $request->input('group_id'), 'user_id' => $this->userId])
            ->first();

        if ($group) {
            // 自己建立的圈子不需要加入
            return $this->jsonResultFail('不需要加入自己建立的圈子');
        }

        $groupJoin = new GroupJoin();
        $groupJoin->user_id = $this->userId;
        $groupJoin->group_id = $request->input('group_id');
        DB::beginTransaction();
        if ($groupJoin->save()) {
            if ($this->groupPP()) {
                DB::commit();
                return ['msg' => 'success'];
            }
        }

        DB::rollBack();
        return $this->jsonResultFail();
    }

    // 新建圈子
    public function add(GroupAdd $request)
    {
        $group = new Group();
        $group->user_id = $this->userId;
        $group->name = $request->get('name');
        $group->background = $request->get('background');
        $group->intro = $request->get('intro');

        if ($group->save()) {
            return ['msg' => 'success'];
        }

        return $this->jsonResultFail();
    }

    // 圈子列表
    public function list(Request $request)
    {
        $page = $request->input('page', 1);
        $lists = Group::query()
            ->where(['status' => 2])
            ->paginate(10, ['id', 'user_id', 'name', 'intro', 'background', 'user_count', 'content_count'], 'page', $page);
        foreach ($lists as $list) {
            $list->UserInfo;
        }
        return $lists;
    }

    public function articleList(Request $request, $id){
        $page = $request->input('page');
        $perPage = $request->input('per_page',10);
        $type = $request->input('type');

        $db = ArticleView::query();
        if($type){
            $db ->where(['type'=>$type]);
        }

        $lists = $db->where(['group_id'=>$id])
            ->paginate($perPage, ['*'], 'page', $page);
        foreach ($lists as $list) {
            $list->userInfo;
        }
        return $lists;
    }

}
